﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System.Text;
using System.Data;
using System.IO;
using System.Collections;

namespace LeSoft.Application.Web.Areas.QualificationManage.Controllers
{

    public class ContractController : MvcControllerBase
    {
        //
        // GET: /QualificationManage/Contract/UndulyIndex
        ContractBussinessBillBLL bll = new ContractBussinessBillBLL();
        ContractAuditBLL Auditbll = new ContractAuditBLL();
        ContractDWellingBLL CDWbll = new ContractDWellingBLL();
        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Detail()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "过渡合同详情", "")]
        public ActionResult UndulyForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "过渡合同业务", "")]
        public ActionResult UndulyFormBussiness()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "过渡合同", "")]
        public ActionResult UndulyIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "过渡合同申请审批", "")]
        public ActionResult TransitionContractIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "过渡合同申请单", "")]
        public ActionResult TransitionContractForm()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "可创建过渡申请数据列表", "")]
        public ActionResult TransitionForm()
        {
            return View();
        }
        #endregion

        #region 查询数据
        /// <summary>
        /// 创建人：hxf
        /// 日  期：2017-09-20
        /// 描  述：获取状态树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList)]
        public ActionResult GetTreeList(string Type)
        {
            List<TreeEntity> treeList = new List<TreeEntity>();
            //treeList.Add(new TreeEntity { id = "All", text = "所有", value = "All", parentId = "0", isexpand = true, complete = true, hasChildren = true });
            //treeList.Add(new TreeEntity { id = "1", text = "我的审批任务", value = "1", parentId = "All", isexpand = true, complete = true, hasChildren = true });
            //treeList.Add(new TreeEntity { id = "11", text = "未审批", value = "11", parentId = "1", isexpand = false, complete = true, hasChildren = false });
            //treeList.Add(new TreeEntity { id = "12", text = "已审批", value = "12", parentId = "1", isexpand = false, complete = true, hasChildren = false });
            //treeList.Add(new TreeEntity { id = "2", text = "所有审批单", value = "2", parentId = "All", isexpand = true, complete = true, hasChildren = true });
            if (string.IsNullOrEmpty(Type) || Type == "All" || Type == "2")
            {
                //treeList.Add(new TreeEntity { id = "21", text = "合同续租", value = "21", parentId = "2", isexpand = false, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "21", text = "所有续租单", value = "21", parentId = "0", isexpand = true, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "211", text = "未提交", value = "211", parentId = "21", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "212", text = "审批中", value = "212", parentId = "21", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "213", text = "已审批", value = "213", parentId = "21", isexpand = true, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "2131", text = "已通过", value = "2131", parentId = "213", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "2132", text = "未通过", value = "2132", parentId = "213", isexpand = true, complete = true, hasChildren = false });
            }
            if (string.IsNullOrEmpty(Type) || Type == "All" || Type == "3")
            {
                //treeList.Add(new TreeEntity { id = "22", text = "合同退租", value = "22", parentId = "2", isexpand = false, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "22", text = "所有退租单", value = "22", parentId = "0", isexpand = true, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "221", text = "未提交", value = "221", parentId = "22", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "222", text = "审批中", value = "222", parentId = "22", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "223", text = "已审批", value = "223", parentId = "22", isexpand = true, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "2231", text = "已通过", value = "2231", parentId = "223", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "2232", text = "未通过", value = "2232", parentId = "223", isexpand = true, complete = true, hasChildren = false });
            }
            if (string.IsNullOrEmpty(Type) || Type == "All" || Type == "1")
            {
                //treeList.Add(new TreeEntity { id = "23", text = "合同变更", value = "23", parentId = "2", isexpand = false, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "23", text = "所有变更单", value = "23", parentId = "0", isexpand = true, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "231", text = "未提交", value = "231", parentId = "23", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "232", text = "审批中", value = "232", parentId = "23", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "233", text = "已审批", value = "233", parentId = "23", isexpand = true, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "2331", text = "已通过", value = "2331", parentId = "233", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "2332", text = "未通过", value = "2332", parentId = "233", isexpand = true, complete = true, hasChildren = false });
            }
            if (string.IsNullOrEmpty(Type) || Type == "All" || Type == "5")
            {
                treeList.Add(new TreeEntity { id = "3", text = "所有单据", value = "3", parentId = "0", isexpand = true, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "31", text = "未提交", value = "31", parentId = "0", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "32", text = "审批中", value = "312", parentId = "0", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "33", text = "已审批", value = "33", parentId = "0", isexpand = true, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "331", text = "已通过", value = "331", parentId = "33", isexpand = true, complete = true, hasChildren = false });
                treeList.Add(new TreeEntity { id = "332", text = "未通过", value = "332", parentId = "33", isexpand = true, complete = true, hasChildren = false });
            }
            return Content(treeList.TreeToJson());
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList)]
        public ActionResult GetPageList(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            if (!string.IsNullOrEmpty(queryJson))
            {
                var queryParam = queryJson.ToJObject();
                if (!queryParam["OrganizeId"].IsEmpty())
                {
                    string OrganizeId = new Cache.OrganizeCache().GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                    queryParam["OrganizeId"] = OrganizeId;
                }
                if (!queryParam["PstructId"].IsEmpty())
                {
                    string PstructId = new Cache.PStructCache().GetSonStructId(queryParam["PstructId"].ToString());
                    queryParam["PstructId"] = PstructId;
                }
                queryJson = queryParam.ToJson();
            }
            var data = bll.GetPageList(pagination, queryJson);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList)]
        public ActionResult GetAuditList(string BussinessId)
        {
            var data = Auditbll.GetList(BussinessId);
            foreach (var item in data)
            {
                item.AuditMan = new AccountBLL().GetEntity(item.AuditMan).IsEmpty() ? "" : new AccountBLL().GetEntity(item.AuditMan).Name;
            }
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList)]
        public ActionResult GetInfo(string keyValue, string ContractId)
        {

            return Content(bll.GetInfo(keyValue, ContractId));
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList)]
        public ActionResult GetEntity(string keyValue)
        {
            var entity = new ContractDWellingBLL().GetCBBEntity(keyValue);
            return Content(entity.ToJson());
        }


        /// <summary>
        /// 获取可过渡数据
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList)]
        public ActionResult GetTransitionContractBussiness(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = Auditbll.GetTransitionContractBussiness(pagination, queryJson);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        /// <summary>
        /// 创建过渡申请
        /// </summary> 
        /// <param name="queryJson"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "创建过渡申请单", "CreateTransitionBussiness")]
        public ActionResult CreateTransitionBussiness(string queryJson)
        {
            try
            {
                Auditbll.CreateTransitionContractBussiness(queryJson);
                return Success("操作成功！");
            }
            catch (Exception e)
            {
                return Error("操作失败：" + e.Message);
            }
        }
        #endregion

        #region 保存数据
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存表单", "SaveForm")]
        public ActionResult SaveForm(string keyValue, string queryJson)
        {
            try
            {
                ContractBussinessBillEntity model = queryJson.ToObject<ContractBussinessBillEntity>();
                bll.ReceiveContractBussiness(keyValue, model);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error(e.Message);
                throw;
            }
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "表单审核", "SaveAuditForm")]
        public ActionResult SaveAuditForm(string queryJson)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                int Level = queryParam["Level"].ToInt();
                string Version = queryParam["Version"].ToString();
                AuditConditionEntity AuditCondition = new AuditConditionEntity();
                List<AuditConditionEntity> lst = new List<AuditConditionEntity>();
                List<AuditConditionEntity> AuditConditionData = new List<AuditConditionEntity>();
                if (queryParam["AuditCondition"].ToString() != "[]") lst = queryParam["AuditCondition"].ToString().ToList<AuditConditionEntity>();
                if (queryParam["AuditConditionData"].ToString() != "[]") AuditConditionData = queryParam["AuditConditionData"].ToString().ToList<AuditConditionEntity>();
                foreach (var item in AuditConditionData)
                {
                    if (item.FieldId != "AuditResult")
                    {
                        AuditConditionEntity aety = lst.Where(e => e.FieldId == item.FieldId).FirstOrDefault();
                        if (!aety.IsEmpty())
                        {
                            if (aety.FieldDate.ToDate()<item.FieldDate.ToDate())
                            {
                                lst.Remove(aety);
                                lst.Add(item);
                            }
                            else
                            {
                                lst.Add(item);
                            }
                        }
                        else
                        {
                            lst.Add(item);
                        }
                    }
                    
                }
                AuditConditionEntity audit = new AuditConditionEntity() { FieldId = "AuditResult", FieldName = "AuditResult", FieldValue = queryParam["AuditState"].ToString(), FieldDate = DateTime.Now };
                lst.Add(audit);

                string WorkAuditSetting = new WorkSettingBLL().GetWorkAuditSetting("退租单", Level, lst, Version);
                int a = 1;
                Auditbll.SaveForm(queryJson, WorkAuditSetting);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error(e.Message + e.InnerException.Message);
                throw;
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "过渡合同申请审核", "AuditTransitionForm")]
        public ActionResult AuditTransitionForm(string queryJson)
        {
            try
            {
                Auditbll.AuditTransitionForm(queryJson);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error(e.Message);
                throw;
            }
        }


        #endregion

        #region 过度合同
        /// <summary>
        /// 合同Id
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "过渡合同保存", "SaveUndulyForm")]
        public ActionResult SaveUndulyForm(string keyValue, string postData)
        {
            ContractDWellingEntity Enty = postData.ToObject<ContractDWellingEntity>();
            ContractDWellingEntity entity = CDWbll.GetContractDWellingEntity(keyValue);
            entity.State = -1;
            entity.SourceId = entity.Id;
            entity.SourceType = 2;
            entity.SignDate = DateTime.Now;
            entity.BeginDate = Enty.BeginDate.ToDate();
            entity.RentYear = Enty.RentYear.ToInt();
            entity.EndDate = Enty.EndDate.ToDate();
            entity.SignDate = DateTime.Now;
            try
            {
                CDWbll.SaveUndulyContract(entity);
                return Success("保存成功");
            }
            catch (Exception e)
            {
                if (e.Message == "费用产生失败") return Success("合同启用成功，产生费用失败！");
                return Error("操作失败：" + e.Message);
            }
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "过渡合同状态树", "GetUndulyCountTreeListTojson")]
        public ActionResult GetUndulyCountTreeListTojson(string OrganizeId)
        {

            List<TreeStatusEntity> lst = new List<TreeStatusEntity>();
            lst.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(ContractEnum.All), ContractEnum.All.ToString(), 0));
            lst.Add(new TreeStatusEntity(ContractEnum.All.ToString(), EnumAttribute.GetDescription(ContractEnum.UnHandled), ContractEnum.UnHandled.ToString(), 0));
            lst.Add(new TreeStatusEntity(ContractEnum.All.ToString(), EnumAttribute.GetDescription(ContractEnum.Current), ContractEnum.Current.ToString(), 0));
            lst.Add(new TreeStatusEntity(ContractEnum.All.ToString(), EnumAttribute.GetDescription(ContractEnum.Complete), ContractEnum.Complete.ToString(), 0));
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (TreeStatusEntity item in lst)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = lst.Count(t => t.PValue == item.Value) == 0 ? false : true;
                tree.id = item.Value;
                tree.text = item.Text;
                tree.value = item.Value;
                if (item.PValue == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.PValue;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "过渡合同表单", "GetUndulyForm")]
        public ActionResult GetUndulyForm(string keyValue)
        {
            var data = CDWbll.GetInfo(keyValue);
            return Content(data);
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "过渡合同详情", "GetUndulyContractInfo")]
        public ActionResult GetUndulyContractInfo(string keyValue)
        {
            return Content(CDWbll.GetUndulyContractInfo(keyValue));
        }

        /// <summary>
        /// 过渡合同保存
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="Type">3 - 启用  5- 结束</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "过渡合同保存", "SaveUndulyBussiness")]
        public ActionResult SaveUndulyBussiness(string keyValue, string Type)
        {
            ContractDWellingEntity entity = CDWbll.GetContractDWellingEntity(keyValue);
            int State = Type.ToInt();
            try
            {
                if (!entity.IsEmpty())
                {
                    entity.State = State;
                    CDWbll.SaveUndulyContract(entity);
                    return Success("操作成功！");
                }
                else
                {
                    return Error("业务类型不能为空");
                }
            }
            catch (Exception e)
            {

                return Error("操作失败：" + e.Message);

            }

        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "数据列表", "GetUndulyList")]
        public ActionResult GetUndulyList(Pagination pagination, string queryJson)
        {
            var data = CDWbll.GetPagList(pagination, queryJson);
            var watch = CommonHelper.TimerStart();
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        #endregion

        #region 合同下载
        /// <summary>
        /// 保存合同文件
        /// </summary>
        /// <param name="ContractId"></param>
        /// <returns></returns>

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存合同文件", "SaveFile")]
        public ActionResult SaveFile(string ContractId)
        {
            try
            {
                string URL = Request.Url.ToString().Replace(Request.RawUrl, "/");
                string FileInfo = new ContractDWellingBLL().DownloadContract(ContractId);
                return Success("保存成功！", FileInfo);
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        /// <summary>
        /// 下载合同
        /// </summary>
        /// <param name="ContractId"></param>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "下载合同", "DownloadContract")]
        public void DownloadContract(string FilePath, string FileName)
        {
            try
            {
                string filename = Server.UrlDecode(FileName);//返回客户端文件名称               
                if (FileDownHelper.FileExists(FilePath))
                {
                    FileDownHelper.DownLoadold(FilePath, filename);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion




    }
}
